package com.frontop.system.modules.file.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.frontop.common.util.JwtUtil;
import com.frontop.common.util.ResultJsonUtil;
import com.frontop.system.config.MultipartFileToFile;
import com.frontop.system.config.NacosConfig;
import com.frontop.system.modules.file.model.SysFile;
import com.frontop.system.modules.file.model.SysFileGroup;
import com.frontop.system.modules.file.service.SysFileGroupService;
import com.frontop.system.modules.file.service.SysFileService;
import com.frontop.system.modules.file.vo.SysFileVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author YangJia
 * @since 2021-12-13
 */
@RestController
@RequestMapping("/sys-file")
public class SysFileController {
    @Autowired
    SysFileService sysFileService;
    @Autowired
    SysFileGroupService sysFileGroupService;
    @Autowired
    NacosConfig nacosConfig;
    @Autowired
    MultipartFileToFile multipartFileToFile;

    @ApiOperation(value = "文件列表")
    @PostMapping("/fileList")
    public ResultJsonUtil<Object> fileList(@RequestBody(required = false) SysFileVO vo, HttpServletRequest request) {
        Page<SysFile> page = new Page<>(vo.getPageNo(),vo.getPageSize());
        page= sysFileService.selectPageVo(page,vo);
        return new ResultJsonUtil().success(page);
    }

    @ApiOperation(value = "文件上传")
    @PostMapping("/uploadFile")
    @Transactional
    public ResultJsonUtil<Object> uploadFile(@RequestParam("files") MultipartFile[] multipartFiles,
                                             @RequestParam("fileRelativePath") String fileRelativePath,
                                             @RequestParam("remark") String remark,
                                             @RequestParam("fileGroup") Integer fileGroup,
                                             @RequestParam("zdjy") Boolean zdjy,
                                             Authentication authentication) throws IOException {
        List<SysFile> files = new ArrayList<>();
        SysFileGroup group = sysFileGroupService.getById(fileGroup);
        String groupPath = null;
        if(group == null){
            return new ResultJsonUtil().fail("分组目录不能为空");
        }else {
            groupPath = group.getFileAbsolutePath();
        }
        String userName = null;
        //整体路径
        String uploadPath = nacosConfig.getUploadPath()+groupPath+fileRelativePath;
        if(multipartFiles.length > 0){
            Claims claims = JwtUtil.getJwtInfo(authentication);
            userName = (String) claims.get("user_name");
            File tempFile = new File(uploadPath);
            if(!tempFile.exists()){
                tempFile.mkdirs();
            }
        }
        for (MultipartFile multipartFile:multipartFiles){
            File tempFile = new File(uploadPath+"/"+multipartFile.getOriginalFilename());
            SysFile sysFile = new SysFile();
            sysFile.setFileName(multipartFile.getOriginalFilename());
            if(multipartFile.getOriginalFilename().indexOf(".") == -1){
                sysFile.setFileType(".file");
            }else {
                String fileType = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
                //判断是否要解压文件
                if(zdjy && fileType.equals(".zip")){
                    multipartFileToFile.decmpression(multipartFile,uploadPath+"/",true);
                }
                sysFile.setFileType(fileType);
            }
            sysFile.setFileSize(multipartFile.getSize() / 1024);
            sysFile.setFileGroup(fileGroup);
            sysFile.setRemark(remark);
            sysFile.setLastUpUser(userName);
            sysFile.setUpdateTime(new Date());
            sysFile.setCreateTime(new Date());
            sysFile.setFileRelativePath(fileRelativePath);
            //下载文件（临时文件需要先保存起来供压缩使用，所以放到最后进行下载）
            multipartFile.transferTo(tempFile);
            files.add(sysFile);
        }

        sysFileService.saveBatch(files);
        return new ResultJsonUtil().success("上传成功");
    }
}